package client.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import packages.Packages;
import client.gui.GUI;

public class Client {

	private int timeout = 1000;

	public Client() {

	}

	public boolean connect(String ip, String name) {
		try {
			// Socket socket = new Socket(ip, 50000);
			Socket socket = new Socket();
			socket.connect(new InetSocketAddress(ip, 50000), timeout);

			OutputStream outStream = socket.getOutputStream();
			InputStream inStream = socket.getInputStream();

			// Sending the player name
			outStream.write(Packages.PACKAGE_PLAYER_NAME);
			outStream.write((name + "\n").getBytes());

			MessageMailBox messageMailBox = new MessageMailBox();
			DrawMailBox drawMailBox = new DrawMailBox();
			ClientIncomingNetwork cin = new ClientIncomingNetwork(inStream,
					messageMailBox, drawMailBox);

			ClientOutgoingMessage com = new ClientOutgoingMessage(outStream,
					messageMailBox);

			ClientOutgoingPosition cop = new ClientOutgoingPosition(outStream,
					drawMailBox);
			

			Drawer drawer = new Drawer(drawMailBox);

			cin.start();
			com.start();
			cop.start();
			drawer.start();

			new GUI(name, messageMailBox, drawMailBox);
		} catch (UnknownHostException e) {
			return false;
		} catch (IOException e) {
			return false;
		}

		return true;
	}

}
